package com.zuiacsn.java_gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

// 房间管理器
@Component
public class RoomManager {
    public ConcurrentHashMap<String,Room> rooms = new ConcurrentHashMap<String,Room>();

    public ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<Integer,String>();

    public void add(Room room, Integer userId1, Integer userId2){
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }

    public void remove(String roomId, Integer userId1, Integer userId2){
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room selectByRoomId(String roomId){
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(Integer userId){
        String roomId = userIdToRoomId.get(userId);
        if(roomId == null){
            // userId --> roomId 映射关系不存在
            return null;
        }
        return rooms.get(roomId);
    }
}
